<template>
	<view class="container">
		<uni-forms ref="form" :modelValue="formData" :rules="rules">
			<uni-forms-item label="设备编号" class="deviceCode">
				<uni-easyinput disabled suffixIcon="scan" @iconClick="scan" type="text" v-model="formData.tagCode"
					placeholder="扫码或手动输入设备编码" />
			</uni-forms-item>
			<uni-forms-item label="设备名称" class="deviceName">
				<uni-easyinput type="text" v-model="formData.tagName" placeholder="请输入设备名称" />
			</uni-forms-item>
			<uni-forms-item label="终端编号" class="deviceName">
				<uni-easyinput disabled type="text" v-model="formData.terminalCode"
					:placeholder="formData.terminalCode" />
			</uni-forms-item>
		</uni-forms>
		<button @click="submit()">保存</button>
	</view>
</template>

<script>
	export default {
		onLoad: function(option) {
			// #ifdef APP-NVUE
			const eventChannel = this.$scope.eventChannel; // 兼容APP-NVUE
			// #endif
			// #ifndef APP-NVUE
			const eventChannel = this.getOpenerEventChannel();
			// #endif
			// 监听acceptDataFromOpenerPage事件，获取上一页面通过eventChannel传送到当前页面的数据
			eventChannel.on('acceptDataFromOpenerPage', (data) => {
				console.log("received: " + data.title)
				this.formData.tagCode = "0000"
				this.formData.tagName = data.title
				this.formData.terminalCode = "1111"
			})
			
			//回复事件及内容：
			// eventChannel.emit('acceptDataFromOpenedPage', {data: 'test'});
			// eventChannel.emit('someEvent', {data: 'test'});
		},

		data() {
			return {
				// 表单数据
				formData: {
					tagName: '',
					tagCode: '',
					terminalCode: ''
				},
				rules: {
					// 对tagCode字段进行必填验证
					tagCode: {
						rules: [{
							required: true,
							errorMessage: '扫码或手动输入设备编码',
						}, ]
					},
					tagName: {
						rules: [{
							required: true,
							errorMessage: '请输入设备名称',
						}, ]
					},
				}
			}
		},
		methods: {
			// 触发提交表单
			submit() {
				this.$refs.form.validate().then(res => {
					console.log('表单数据信息：', res);
				}).catch(err => {
					console.log('表单错误信息：', err);
				})

				// #ifdef APP-NVUE
				const eventChannel = this.$scope.eventChannel; // 兼容APP-NVUE
				// #endif
				// #ifndef APP-NVUE
				const eventChannel = this.getOpenerEventChannel();
				// #endif
				//回复事件acceptDataFromOpenedPage
				eventChannel.emit('acceptDataFromOpenedPage', this.formData);
				
				console.log("you clicked save, then we will back..");
				
				uni.navigateBack({
					delta:1
				})
			},
			// 扫码
			scan() {
				console.log("you clicked scan..");
			}
		}
	}
</script>

<style>
	.container {
		padding: 20px;
		font-size: 14px;
		line-height: 24px;
	}

	.tagCode {
		margin: auto;
	}
</style>
